package main

import (
	"strconv"
	"strings"
	"fmt"
	"regexp"
)

const root = "htdocs"

const (
	get = iota
	post
)

const (
	noerr = iota
	unimplement
	bad_request
)

type header struct {
	method int
	url string
	query string
	content_len string
	cgi bool
	fail int
}

func parse_display (stat header) {
	fmt.Println ("URL : ", stat.url)
	fmt.Println ("QUERY : ", stat.query)
	fmt.Println ("CONTENT_LENGTH : ", stat.content_len)
	fmt.Println ("CGI : ", stat.cgi)
	fmt.Println ("PARSE_RESULT : ", stat.fail)
}

func parse_try_to_get_header (buf string) int {
	return strings.Index (buf, "\r\n\r\n")
}

func parse_get_url (head string) string {
	url := root
	url += head[:strings.Index (head[:], " ")]
	if (url[len (url) - 1] == '/') {
		url += "index.html"
	}
	return url
}

func parse_header (head string) header {
	var stat header
	stat.cgi = false
	stat.fail = noerr
	if (strings.EqualFold (head[:3], "GET")) {
		stat.method = get
		url := parse_get_url (head[4:])
		off := strings.Index (url, "?")
		if (off != -1) {
			stat.cgi = true
			stat.url = url[:off]
			stat.query = url[off:]
		} else {
			stat.url = url
		}
	} else if (strings.EqualFold (head[:4], "POST")) {
		reg := regexp.MustCompile (`Content-Length: (\d+)\r\n`)
		stat.content_len = reg.FindStringSubmatch (head)[1]
		if val, _ := strconv.Atoi (stat.content_len); val == 0 {
			stat.fail = bad_request
			return stat
		}
		stat.method = post
		stat.cgi = true
		stat.url = parse_get_url (head[5:])
	} else {
		stat.fail = unimplement
	}
	//parse_display (stat)
	return stat
}
